#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import decimal
import json
import uuid
from django.http.response import HttpResponse


class RevisedDjangoJSONEncoder(json.JSONEncoder):
    """
    JSONEncoder subclass that knows how to encode date/time and decimal types.
    """
    def default(self, o):
        # See "Date Time String Format" in the ECMA-262 specification.
        if isinstance(o, datetime.datetime):
            r = o.strftime('%Y-%m-%d %H:%M:%S')
            if o.microsecond:
                r = r[:23] + r[26:]
            if r.endswith('+00:00'):
                r = r[:-6] + 'Z'
            return r
        elif isinstance(o, datetime.date):
            return o.isoformat()
        elif isinstance(o, datetime.time):
            #if is_aware(o):
            #    raise ValueError("JSON can't represent timezone-aware times.")
            r = o.isoformat()
            if o.microsecond:
                r = r[:12]
            return r
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, uuid.UUID):
            return str(o)
        else:
            return super(RevisedDjangoJSONEncoder, self).default(o)


class JsonResponseMiddleware(object):
    def process_response(self, request, response):
        if isinstance(response, dict):
            # MH 格式化response,方便开发过程中查看返回的json数据
            # 去掉返回的json中的空格,减少数据量
            data = json.dumps(response, indent=4, separators=(',', ': '), cls=RevisedDjangoJSONEncoder)
            # data = json.dumps(response, cls=RevisedDjangoJSONEncoder)
            if 'callback' in request.REQUEST:
                data = '%s(%s);' % (request.REQUEST['callback'], data)
                return HttpResponse(data, "text/javascript")
            # return HttpResponse(data, "application/json")
            # IE会对json response弹出下载文件框，所以不使用application/json
            return HttpResponse(data)
        else:
            return response

def create_failure_dict(**kwargs):
    ret = {'status': 'failure'}
    ret.update(kwargs)
    return ret


def create_success_dict(**kwargs):
    ret = {'status': 'success'}
    ret.update(kwargs)
    return ret
